<!--
 * @Author: huCheng Li
 * @Date: 2023-10-20 21:04:03
 * @description: 
 * @LastEditTime: 2023-10-27 14:27:02
 * @FilePath: \三阶段\pilipili\pili-pili-app\src\pages\login\login.vue
-->
<template>
  <div class="login-box">

    <van-nav-bar @click="changeStatus" right-text="切换登录" left-arrow />

    <header>

      <div class="brand">pilipili&nbsp;&nbsp;&nbsp;<span>开启快乐生活!</span></div>

    </header>

    <div class='line'>
      <van-field required label="手机号" v-model.trim="phone" placeholder="请输入手机号" />
    </div>
    <div class='line' v-show="showpsd">
      <van-field v-model.trim="password" required :type='!showeye ? "password" : "text"' label="密码" />
    </div>
    <span class="status">
      <van-icon name="closed-eye" v-show="!showeye" @click="changeEyes" />
      <van-icon name="eye-o" v-show="showeye" @click="changeEyes" />
    </span>
    <div class='line' v-show="showcode">
      <van-field center clearable v-model.trim="code" placeholder="请输入短信验证码">
        <template #button>
          <van-button size="small" @click="getCodeEvt" type="primary">{{ msgs }}</van-button>
        </template>
      </van-field>
    </div>
    <div class="ckbox">

      <van-checkbox v-model="remember" shape="square">是否记住手机号？</van-checkbox>

    </div>
    <div class="ckbox">

      <van-checkbox v-model="auto" shape="square">是否同意免登陆？</van-checkbox>

    </div>
    <div class="btn">
      <van-button type="primary" size="large" @click="loginEvt" :loading="loading"
        :disabled="showcode ? !canLogin : !canLogins">验证登录</van-button>
    </div>

    <div class="ckbox">
      <van-checkbox v-model="checked" shape="square">我已阅读并同意
        <span @click="router.push('/conts')">用户使用协议</span>
      </van-checkbox>
      <span class="gore" @click="router.push('/register')">去注册

      </span>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { showToast } from "vant";
import { Ref, ref } from "vue";
import { Router, useRouter } from "vue-router";
import { getVdtCodeApi, userLoginApi, usePsdApi } from "../../apis/userApis";
import { AUTO_LOGIN, REMEMBER_PHONE, GET_HEAD, GET_NAME, } from "../../config/common.cfg";
import { onMounted } from "vue";
import { decodeApi, encodeApi } from "../../utils";
import { ComputedRef } from "vue";
import { computed } from "vue";
import { Md5 } from 'ts-md5';


// import { storeToRefs } from "pinia";
import { useCommonStore } from "../../store";
// import { USER_PWD_LOGIN_URL } from "../../config/urls.cfg";
const showcode: Ref<boolean> = ref(true);
const showpsd: Ref<boolean> = ref(false);
let showeye: Ref<boolean> = ref(false);
const router: Router = useRouter();
const code: Ref<string> = ref('')
const phone: Ref<number> = ref(1);
const password: Ref<string> = ref("");
const checked: Ref<boolean> = ref(false);
const remember: Ref<boolean> = ref(false);
const auto: Ref<boolean> = ref(false);
const msgs: Ref<string> = ref('获取验证码');
const store = useCommonStore();
const md5: any = new Md5()
//初始化时验证?????
onMounted(function () {
  let _rem = localStorage.getItem('REMEMBER_PHONE')
  if (_rem) {
    phone.value = parseInt(decodeApi(_rem))
    remember.value = true
  }
  if (localStorage.getItem('AUTO_LOGIN')) {
    router.push('/home')
    showToast("免登录成功!")
  }
})
//正则验证手机号不符合条件按钮不可用
function checkPhone(phone: number): boolean {
  return /^1[3-9]{1}[0-9]{9}$/.test(phone + '');
}
const canLogin: ComputedRef<boolean> = computed(() => {

  return checked.value && checkPhone(phone.value) && /^[0-9]{4}$/.test(code.value)
})

const canLogins: ComputedRef<boolean> = computed(() => {
  return checked.value && checkPhone(phone.value) && password.value.length >= 3
})
//获取验证码
async function getCodeEvt() {
  if (!checkPhone(phone.value)) {
    showToast('请输入正确的手机号')
    return
  }

  console.log(showcode.value);

  if (msgs.value !== '获取验证码') {
    return
  }
  msgs.value = '获取中...'
  let _res = await getVdtCodeApi(phone.value)
  if (_res.code === 200) {
    msgs.value = '重新获取(60s)'
    showToast('验证码:' + _res.data.code)

    loopTimer(Date.now())
    console.log(_res.data.code);
  } else {
    msgs.value = '获取验证码'
    showToast('获取验证码失败!')
  }



}

// 验证码倒计时
function loopTimer(_st: number) {
  let _time = 60 - Math.ceil((Date.now() - _st) / 1000)

  if (_time > 0) {
    msgs.value = `重新获取(${_time}s)`
    setTimeout(function () {
      loopTimer(_st)
    }, 100)
  } else {
    msgs.value = `获取验证码`
  }
}

//登陆失败禁用登录
const loading: Ref<boolean> = ref(false);
async function loginEvt() {
  loading.value = true;
  if (showcode.value == true) {
    console.log(showcode.value);

    let _res = await (userLoginApi(phone.value + '', code.value));
    console.log(_res);

    if (_res.code !== 200) {
      showToast("登陆失败," + _res.message)
      console.log(code.value);


      return

    } else {
      store.token = _res.data.token;
      store.userInfo = _res.data.userInfo;
      localStorage.setItem(GET_HEAD, _res.data.photo)
      localStorage.setItem(GET_NAME, _res.data.name)
    }
    //记住手机号
    if (remember.value) {
      localStorage.setItem(REMEMBER_PHONE, encodeApi(phone.value + ''))
    } else {
      localStorage.removeItem(REMEMBER_PHONE)
    }
    //免登录
    if (auto.value) {
      localStorage.setItem(AUTO_LOGIN, encodeApi(_res.data.token))
    } else {
      localStorage.removeItem(AUTO_LOGIN)
    }
    showToast("登录成功!")
    localStorage.setItem('userid', phone.value + '')
    router.push('/home')
  }
  else {
    md5.appendAsciiStr(password.value)
    let psd = md5.end()
    let _res = await usePsdApi(phone.value + '', psd)
    console.log(_res.code);
    console.log(psd);


    if (_res.code === 200) {
      console.log(password.value);

      showToast('登陆成功')
      store.token = _res.data.token;
      store.userInfo = _res.data.userInfo;
      localStorage.setItem(GET_HEAD, _res.data.photo)
      localStorage.setItem(GET_NAME, _res.data.name)
    } else {
      showToast('账号或密码错误!')
      loading.value = false;
      return
    }
    if (remember.value) {
      localStorage.setItem(REMEMBER_PHONE, encodeApi(phone.value + ''))
    } else {
      localStorage.removeItem(REMEMBER_PHONE)
    }
    //免登录
    if (auto.value) {
      localStorage.setItem(AUTO_LOGIN, encodeApi(_res.data.token))
    } else {
      localStorage.removeItem(AUTO_LOGIN)
    }
    showToast("登录成功!")
    localStorage.setItem('userid', phone.value + '')
    router.push('/home')
  }
  //记住手机号


}

function changeStatus() {
  // console.log(233);
  showcode.value = !showcode.value;
  showpsd.value = !showpsd.value;

}
function changeEyes() {
  showeye.value = !showeye.value

}

</script>
<style lang = "less" scoped>
@import "../../style/common.less";



.login-box {
  .rel();


  header {
    height: 80px;
    width: 100%;
    background: @b1;

    .brand {
      position: relative;
      text-align: center;
      // margin-top: 20px;
      font-size: 26px;
      font-weight: 600;
      color: @b5;
      padding-top: 16px;

      &::before {
        content: '';
        display: inline-block;
        // vertical-align: bottom;
        width: 50px;
        height: 50px;
        background: url(../../images/22_open.4ea5f239.png) center center / 100% 100% no-repeat;
        margin-right: 10px;
        position: absolute;
        top: 30px;
        left: 0;
      }

      &::after {
        content: '';
        display: inline-block;
        vertical-align: bottom;
        width: 50px;
        height: 50px;
        background: url(/src/images/33_open.f7d7f655.png) center center / 100% 100% no-repeat;
        position: absolute;
        top: 30px;
        right: 0;
      }

      span {
        font-size: 16px;
      }


    }
  }

  .line {
    border-bottom: 1px solid @g05;

    :deep(.van-cell--center) {
      height: 44px;
    }
  }

  .status {
    position: absolute;
    height: 20px;
    /* background: antiquewhite; */
    width: 20px;
    top: 183px;
    right: 16px;
  }

  .btn {
    margin-top: 20px;
  }

  .ckbox {
    font-size: 13px;
    margin-top: 20px;

    span {
      color: @b4;
    }

    .gore {
      position: absolute;
      top: 386px;
      right: 5px;
    }
  }

  .ckboxs {
    // display: flex;
    // justify-content: space-around;
    font-size: 13px;
    margin-top: 20px;
  }
}
</style>
 